package com.edu.internship.busi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.edu.internship.busi.dto.UserDTO;
import com.edu.internship.busi.entity.User;
import com.edu.internship.busi.mapper.UserMapper;
import com.edu.internship.busi.service.IUserService;
import com.edu.internship.config.cache.GuavaCache;
import com.edu.internship.glabal.constants.Constants;
import com.edu.internship.glabal.constants.ResultCodeEnum;
import com.edu.internship.glabal.exception.BusinessException;
import com.edu.internship.util.BeanExUtils;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;

/**
 * [一句话描述该类的功能]
 *
 * @author : tianhuida
 * @version : [v1.0]
 * @createTime : [2022/8/2 9:45]
 */
@Service
@AllArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    private GuavaCache guavaCache;

    @Override
    @Transactional(rollbackFor = BusinessException.class)
    public void createUser(UserDTO dto){
       User user = this.nonExistsAndConvert(dto);
       user.setCreateTime(LocalDateTime.now());
       user.setUpdateTime(LocalDateTime.now());
        super.save(user);
    }

    @Override
    @Transactional(rollbackFor = BusinessException.class)
    public void updateUser(UserDTO dto) {
        User db = super.getById(dto.getId());
        guavaCache.del(Constants.RedisKeyCons.DICTIONARY.getCode() + db.getUsername());
        User user;
        if (!Objects.equals(db.getId(), dto.getId())) {
            user = this.nonExistsAndConvert(dto);
        } else {
            user = BeanExUtils.convertTo(dto, User::new);
        }
        user.setUpdateTime(LocalDateTime.now());
        super.updateById(user);
    }

    @Override
    @Transactional(rollbackFor = BusinessException.class)
    public void removeUser(List<String> id) {
        super.removeByIds(id);
    }


    private User nonExistsAndConvert(UserDTO dto) {
        LambdaQueryWrapper<User> qw = Wrappers.lambdaQuery();
        qw.eq(User::getUsername, dto.getUsername());
        if (super.count(qw) > 0) {
            throw new BusinessException(ResultCodeEnum.USE_NAME_EN_EXISTS);
        }
        return BeanExUtils.convertTo(dto, User::new);
    }
}
